/*
 * ConnectionInfo.java
 */

package xq.ide;

import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import static xq.util.CommonUtil.blank;
import static xq.util.CommonUtil.empty;

/**
 *
 * @author ThorntonRP
 */
public class ConnectionInfo {

	private String name;
	private String userName;
	private String password;
	private String hostName;
	private String portNumber;
	private String uriPattern;
	private URI connectionURI;

	public ConnectionInfo(String name, String userName, String password, String hostName, String portNumber, String uriPattern) throws URISyntaxException {
		setName(name);
		setUserName(userName);
		setPassword(password);
		setHostName(hostName);
		setPortNumber(portNumber);
		setURIPattern(uriPattern);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) throws URISyntaxException {
		if (blank(name)) {
			throw new IllegalArgumentException("Connection name is required.");
		}
		this.name = name;
		updateConnectionURI();
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) throws URISyntaxException {
		if (empty(password)) {
			throw new IllegalArgumentException("Password is required.");
		}
		this.password = password;
		updateConnectionURI();
	}

	public String getHostName() {
		return hostName;
	}

	public void setHostName(String hostName) throws URISyntaxException {
		if (blank(hostName)) {
			throw new IllegalArgumentException("Host name is required.");
		}
		this.hostName = hostName;
		updateConnectionURI();
	}

	public String getPortNumber() {
		return portNumber;
	}

	public void setPortNumber(String portNumber) throws URISyntaxException {
		if (blank(portNumber)) {
			throw new IllegalArgumentException("Port number is required.");
		} else if (!portNumber.matches("\\d+")) {
			throw new IllegalArgumentException("Port number must be an integer value.");
		}
		this.portNumber = portNumber;
		updateConnectionURI();
	}

	public String getURIPattern() {
		return uriPattern;
	}

	public void setURIPattern(String uriPattern) throws URISyntaxException {
		if (blank(portNumber)) {
			throw new IllegalArgumentException("Connection URI pattern is required.");
		}
		this.uriPattern = uriPattern;
		updateConnectionURI();
	}

	public URI getConnectionURI() {
		return connectionURI;
	}

	@Override
	public String toString() {
		return name;
	}

	private void updateConnectionURI() throws URISyntaxException {
		if (uriPattern != null &&
				userName != null &&
				password != null &&
				hostName != null &&
				portNumber != null) {
			String uri = MessageFormat.format(
					uriPattern,
					userName,
					password,
					hostName,
					portNumber);
			connectionURI = new URI(uri);
		}
	}
}
